package com.example.demo.common;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 黑名单
 */
@Component("blacklist")
public class blacklist {
    //存储每个ip的访问次数
    private final Map<String,Integer> accessCount = new ConcurrentHashMap<>();
    //将指定ip放到黑名单中
    public void blockIp(String ip){
        accessCount.put(ip,0);
    }

    //将指定ip从黑名单中移除
    public void unblockIp(String ip){
        accessCount.remove(ip);
    }

    //判断指定ip是否在黑名单中
    public boolean isIpBlocked(String ip){
        Integer count = accessCount.get(ip);

        //如果次数大于规定值放入黑名单
        return count != null && count>=3;
    }
    //返回所有在黑名单中的ip
    public Map<String ,Integer> getBlockedIp(){
        Map<String,Integer> blockedIp = new HashMap<>();
        for (Map.Entry<String,Integer> entry:accessCount.entrySet()){
            String ip = entry.getKey();
            Integer count = entry.getValue();

            //指定Ip访问次数大于固定值，拉入黑名单
            if (count>=3){
                blockedIp.put(ip,count);
            }
        }

        return blockedIp;
    }


    //清空黑名单,重置次数
    public void clear(){
        accessCount.clear();
    }
}
